//
//  FWVersionChecker.m
//  JSONCheck
//
//  Created by 范武 on 12-11-6.
//  Copyright (c) 2012年 fanwu. All rights reserved.
//

#import "FWVersionChecker.h"
#import "AFNetworking.h"
#import "UIUtil.h"

#define kVersionJson    @"http://61.154.10.49:9521/patrol_test/version.json"
#define kAppAddr @"http://61.154.10.49:9521/patrol_test/"



@implementation FWVersionChecker

static FWVersionChecker * _instance;

+ (void)initialize
{
    _instance = [[FWVersionChecker alloc]init];
}

+ (id)shareInstace
{
    if (!_instance) {
        _instance = [[FWVersionChecker alloc]init];
    }
    return _instance;
}



- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (NSUInteger )localVersion
{
    NSDictionary * infoDict = [[NSBundle mainBundle] infoDictionary];
    NSUInteger  version = [[infoDict objectForKey:@"buildNO"] integerValue];
    return version;
}


- (BOOL) compareLocalVersion:(NSUInteger )localBuildNO WithNetVersion:(NSUInteger)netBuildNO
{
    if (netBuildNO > localBuildNO) {
        [UIUtil alertOKCancelWithTitle:@"提示" withMsg:@"有新版本发布，是否立即更新？" withDelegate:self];
        return YES;
    }
    return  NO;
}

- (void)compareVersion
{
    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:kVersionJson]];
    AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSUInteger remoteBuildNO = [[JSON objectForKey:@"BuildNo"] integerValue];
        NSUInteger localBuildNO = [self localVersion];
        [self compareLocalVersion:localBuildNO WithNetVersion:remoteBuildNO];
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        //忽略还是做别的啥？
    }];
    
    [operation start];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:kAppAddr]];
    }
}

@end
